var Form83;

(function(){

	var _Pool	= {};

	var beforValidate	= function(){
		if( this.isSubmit ) {
			alert('表单已经递交!');
			return true;
		}
		var submit	= window[ this.dom.id + '_submit'];
		if( typeof submit == 'function' ){
			try{
				if( !submit.call(this.dom) )
					return true;
			}catch(e){}
		}
	}
	var afterValidate	= function(){
		var submit	= window[ this.dom.id + '_submit1'];
		if( typeof submit == 'function' ){
			try{
				if( !submit.call(this.dom) )
					return true;
			}catch(e){}
		}
		this.isSubmit	= true;
	}

	Form83 = new Class({
		id : null,
		dom : null,
		isSubmit : false,
		attrs : {},
		vals : {},

		initialize: function(id, callback, attrs, vals ){
			this.id		= id;
			this.dom	=  $(id).getParent('form');
			if( !this.dom ){
				return false;
			}
			if( typeof(callback) != 'function' ){
				callback	= function(){}
			}
			if( typeof(attrs) == 'object' ){
				this.attrs	= attrs;
			}
			if( typeof(vals) == 'object' ){
				this.vals	= vals;
			}
			window.addEvent('domready', function(){
				this.InitForm();
				this.dom.addEvent('submit', function(evt){
					var funs = [beforValidate, callback, afterValidate];
					for(var i = 0; i<funs.length; i++){
						if( funs[i].call(this) ){
							evt.stop();
							return false;
						}
					}
				}.bind(this));
				try{Sched.Init();}catch(err){}
			}.bind(this));
		},

		InitForm : function(){
			var f83		= this.dom;
			
			// handle ShowOn elements
			$each(this.attrs, function( attrs , name){
				if( typeof( attrs['ShowOn'] ) != 'object' ){
					return ;
				}
				var elements	= f83.getElements("*[name="+name+"]");
				if( elements.length == 0 ){
					elements	= $$( document.getElementsByName( name + "[]") );
				}
				if( elements.length > 0 ){
					var element	= elements[0].getParent('.f83e');

					if( !element ){
						alert("element `" + name + "` missing parent" );
						return ;
					}
					element.retrieve('__display', 'none');


					var byElements	= [] ;
					$each(attrs['ShowOn'], function(vals, byName){
						var ec	= f83.getElements('*[name='+byName+']');
						if( ec.length == 0 ){
							ec	= $$( document.getElementsByName(byName + "[]") );
						}
						if( ec.length == 0 ){
							return;
						}
						var bye = ec[0].getParent('.f83e');
						if( !bye ){
							alert('missing parent ' + byName );
							return ;
						}
						var p = { 'i': (ec[0].tagName == 'SELECT') , 'c': ec , 'p':bye };
						p.v	= vals.map(function(v){
							return String(v);
						});
						byElements.push( p );
					});

					function testShowOn(){
						element.setStyle('display',
							byElements.some(function( a ){
								if( a.i ){
									return a.v.indexOf( String(a.c[0].value) ) >= 0 ;
								}else{
									return a.c.some(function(el){
										return (el.checked && a.v.indexOf( String(el.value) ) >=0);
									});
								}
							})
						? '' : 'none' );
						element.store('__display', element.getStyle('display'));
						element.fireEvent('display');
					}

					byElements.each(function( a ){
						a.p.addEvent('display', function(){
							var display	= a.p.getStyle('display');
							if(  display === 'none' ){
								element.setStyle('display', 'none');
							}else{
								element.setStyle('display', element.retrieve('__display'));
							}
							element.fireEvent('display');
						});
						if( a.i ){
							a.c.addEvent('change', testShowOn);
						}else{
							a.c.addEvent('click', testShowOn);
						}
					});
					setTimeout(testShowOn, 300);
				}
			});

			var _Url	= (typeof _RootDir == 'string' ?  _RootDir : '.' ) + "/_admin/param.php?id=";

			// handle ShowBy elements
			$each(this.attrs, function( attrs , name ){
				if( typeof( attrs['ShowBy'] ) != 'string' ){
					return ;
				}
				var byName	= attrs['ShowBy'];
				var byElements		= f83.getElements("select[name=" + byName + "]");
				if( byElements.length == 0 ){
					return ;
				}
				var bySel	= byElements[0];
				var elements		= f83.getElements("select[name=" + name + "]");
				if( elements.length == 0 ){
					return ;
				}
				var sel	= elements[0];
				var _id	= parseInt( sel.getProperty("val") );

				function OnLoaded(txt){
					var o	= JSON.decode(txt);
					for(var i in o){
						new Element("option", {'value':i, text:  o[i]}).inject(sel);
					}
					if( _id && o[_id] ) {
						sel.getElement("option[value="+_id+"]")
							.addClass("selected")
								.setAttribute("selected",  "selected");
					}
					if( Browser.Engine.trident ){
						setTimeout(function(){
							sel.fireEvent('change');
						}, 20);
					}else{
						sel.fireEvent('change');
					}
				}
				bySel.addEvent('change', (function(evt){
					sel.empty();
					if( !bySel.value  ){
						return arguments.callee;
					}
					if( _Pool[bySel.value] ){
						OnLoaded(_Pool[bySel.value]);
						return ;
					}
					var url	=  _Url + bySel.value ;
					new Request({
						url:  url,
						method: 'get',
						onSuccess : function(txt){
							_Pool[bySel.value]	= txt;
							OnLoaded(txt);
						}
					}).send();
					return arguments.callee;
				})());
				
			});

			//handel vals
			var _Vals	= this.vals;
			function CheckIt(){
				$each(_Vals , function(val, name){
					var vals	= val.trim().split(/\s*,\s*/).filter(function(val){
						return  val != '';
					});
					var ec	= $$( document.getElementsByName(name+"[]")  );
					if( !ec.length || ec[0].getParent('form') != f83  ){
						return ;
					}
					ec.each( function(el){
						if( el.tagName !='INPUT' || el.getAttribute('type') != 'checkbox' ){
							return ;
						}
						if( vals.indexOf ( el.value ) >=0 ){
							el.checked	= true;
						}
					});
				});
			}
			CheckIt();
			
			var _attrs	= this.attrs;
			function onReSet(){
				CheckIt();
				$each(_attrs, function( attrs , name ){
					if( typeof( attrs['ShowBy'] ) != 'string' ){
						return ;
					}
					var elements		= f83.getElements("select[name=" + name + "]");
					if( elements.length == 0 ){
						return ;
					}
					var sel	= elements[0];
					var _id	= parseInt( sel.getProperty("val") );
					var option	= sel.getElements("[value="+_id+"]");
					if( option.length ){
						option[0].setAttribute("selected",  "selected");
					}else{
						var byName	= attrs['ShowBy'];
						var byElements		= f83.getElements("select[name=" + byName + "]");
						if( byElements.length == 0 ){
							return ;
						}
						var bySel	= byElements[0];
						bySel.fireEvent('change');
					}
				});

				$each(_attrs, function( attrs , name){
					if( typeof( attrs['ShowOn'] ) != 'object' ){
						return ;
					}
					$each(attrs['ShowOn'], function(vals, byName){
						var byElements	= f83.getElements('*[name='+byName+']');
						if( byElements.length == 0 ){
							byElements	= $$( document.getElementsByName(byName + "[]") );
						}
						if( byElements.length == 0 ){
							return;
						}
						if( byElements[0].tagName != 'SELECT' ){
							byElements[0].fireEvent('click');
						}
					});
				});
			}
			var Timer2;
			f83.addEvent('reset', function(){
				$clear(Timer2);
				Timer2	= setTimeout(onReSet, 200);
			});
			
		}
	});
})();

window.addEvent('domready', function(){
	try{

		function _set(el, col, isBack ){
			if( isBack ){
				var hsb	= col.hsb ;
				hsb[0]	+=	( hsb[0] > 180 ? -2 : 2 ) ;
				hsb[1]	+=	( hsb[1] > 50 ? -40 : 40 ) ;
				hsb[2]	+=	( hsb[2] > 50 ? -40 : 40 ) ;
				el.setStyle('color', new Color(hsb, 'hsb') );
				el.setStyle('background-color', col );
			}else{
				el.setStyle('color', col);
				el.setStyle('background-color',  '#fff');
			}
		}

		function _get(el){ return new Color( el.value =='' ? '#000' : el.value) ; }
		$$('input.MooColor').each(function(el){
			var _col	= _get(el);
			_set(el, _col);	
			var ex1 = new MooRainbow(el, {
				'parent' : 'html',
				'startColor': _col.rgb , 
				'onShow': function(){
					var col	= _get(this.element);
					this.manualSet(col);
				},
				'onCancel': function(color){
					_set( this.element, _get(this.element) );
				},
				'onChange':function(color){
					var col	= new Color( color.hex );
					_set(this.element, col, true);
				},
				 'onComplete': function(color) {
					this.element.value =  color.hex ; 
					_set(this.element, color.hex);
				}
			});
		});
	}catch(e){}

});

